package top.cardone.beans;

import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.FactoryBean;
import top.cardone.context.ApplicationContextHolder;

import java.util.LinkedHashMap;

/**
 * json 字符串解析为对象
 * Created by yao hai tao on 2015/5/22.
 */
public class JsonStringFactoryBean implements FactoryBean<Object> {
	@lombok.Setter
	private String jsonString;

	@lombok.Setter
	@lombok.Getter
	private Class<?> objectType;

	@lombok.Setter
	@lombok.Getter
	private boolean singleton;

	private Object object;

	@Override
	public Object getObject() throws Exception {
		if (StringUtils.isBlank(jsonString)) {
			return null;
		}

		if (BooleanUtils.isTrue(singleton) && object != null) {
			return object;
		}

		if (objectType == null) {
			object = ApplicationContextHolder.getBean(Gson.class).fromJson(jsonString, new TypeToken<LinkedHashMap<String, Object>>() {
			}.getType());
		} else {
			object = ApplicationContextHolder.getBean(Gson.class).fromJson(jsonString, objectType);
		}

		return object;
	}
}
